from Spider.BingImageSpider import BingImageSpider
from Spider.BaiduImageSpider import BaiduImageSpider
from Spider.Downloader import Downloader
from Utils.ImageUtils import *
from Utils.Common import removeFile, removeDir, getMachineMemoryInfo
from multiprocessing.dummy import Pool as ThreadPool
import cv2
import os, platform
import subprocess as sp


class Assistant():
    def __init__(self, logger, save_dir):

        super(Assistant, self).__init__()
        self.logger = logger
        self.__save_dir = save_dir
        platform_system = platform.system()
        self.logger.info("当前操作系统：%s，文件存储根目录：%s" % (platform_system, self.__save_dir))

    def run(self, seed, page_count=5):
        self.logger.info("start")

        # imageSpider = BaiduImageSpider(logger=self.logger, proxy_radio=0)
        imageSpider = BingImageSpider(logger=self.logger, proxy_radio=0)
        downloader = Downloader(logger=self.logger, proxy_radio=0)

        pool = ThreadPool(20)
        seed_name = seed.get("name")

        imageArray = []
        bingImageArray = imageSpider.searchImageArray(seed_name, pageCount=page_count)

        for d in bingImageArray:
            imageArray.append({
                "url_source": d.get("url_source"),
                "url_source_org": d.get("url_source_org"),
                "name": d.get("name"),
                "platform_id": imageSpider.platform_id
            })

        # 获取图片下载的种子 end
        group1ImageArray = []  # 下载的过滤后的图片数组

        def __download(d):
            try:
                download_state, content = downloader.exec(d.get("url_source"))
                if download_state:
                    image_org = cv2.imdecode(np.frombuffer(content, np.uint8), cv2.IMREAD_COLOR)
                    h, w, c = image_org.shape
                    w_h = float(w / h)
                    image_org_articulate = calcuImageArticulate(image_org)  # 计算原图的清晰度

                    # if h > 400 and w_h > 1.1 and w_h < 2.5 and image_org_articulate > 300:
                    if True:
                        self.logger.info("下载成功: %s" % str(d))

                        d["image_org"] = image_org
                        d["image_org_articulate"] = image_org_articulate
                        d["image_org_dark"] = calcuImageDark(image_org)  # 计算原图的暗色占比
                        group1ImageArray.append(d)
                else:
                    raise Exception(content)
            except Exception as e:
                self.logger.error("下载失败: %s|%s" % (str(d), str(e)))

        t1 = time.time()
        pool.map(__download, imageArray)
        t2 = time.time() - t1

        count = len(imageArray)
        group1ImageCount = len(group1ImageArray)

        mem_percent, mem_used, mem_left, mem_total = getMachineMemoryInfo()

        self.logger.info(
            "mem_percent=%.2f,mem_total=%d,count=%d,group1ImageCount=%d,spend:%.2f(s)" % (
                mem_percent, mem_total, count, group1ImageCount, t2))

        self.__handleGroup1ImageArray(seed, group1ImageArray)

    def __handleGroup1ImageArray(self, seed, group1ImageArray):

        t1 = time.time()
        seed_name = seed.get("name")
        seed_name_en = seed.get("name_en")

        ### 注意注意，首先按照图片的亮度降序
        # group1ImageArray.sort(key=lambda x: x.get("image_org_dark"), reverse=False)

        imageDir = os.path.join(self.__save_dir, "%s" % seed_name_en)
        if not os.path.exists(imageDir):
            os.makedirs(imageDir)

        for i, d in enumerate(group1ImageArray):
            try:
                # url_source = d.get("url_source")
                # url_source_org = d.get("url_source_org")
                # name = d.get("name")
                platform_id = d.get("platform_id")
                image_org = d.get("image_org")
                image_org_articulate = d.get("image_org_articulate")
                image_org_dark = d.get("image_org_dark")

                image_path_abs = os.path.join(imageDir, "%s-%d_%d_%.2f_%d.jpg" % (
                    seed_name_en,platform_id, i, image_org_dark, image_org_articulate))

                cv2.imwrite(image_path_abs, image_org)

            except Exception as e:
                self.logger.error(str(e))

        t2 = time.time() - t1
        self.logger.info("spend:%.2f(s)" % (t2))
